<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2020/9/1
 * Time: 16:42
 */
namespace app\shop\controller;
use think\Db;
class Order extends Base
{
    //首页
    public function index()
    {
        extract(input());
        $page = input('param.page');
        $user_id = session('user_id');
        $search = input('param.search/a');

        if(!$page){
            $pages = 0;
        }else{
            $pages = $page-1;
        }
        $search = $this->search($search, $page);
        //搜索条件
        $map = [];
        //任务编号/手机号
        if($search[0] != ""){
            $map['a.order_num|a.order_goods_name'] = ['like',"%" . $search[0] . "%"];
        }
        $map['a.order_type'] = array('not in',array(3,4));
        $data = Db::table('up_order')->alias('a')
            ->join('up_car_hwlx uch','uch.hwlx_id = a.hwlx_id','left')
            ->join('up_car_zxlx ucz','ucz.zxlx_id = a.zxlx_id','left')
            ->join('up_area ua','ua.district_id = a.order_go_sheng','left')
            ->join('up_area ua1','ua1.district_id = a.order_go_shi','left')
            ->join('up_area ua2','ua2.district_id = a.order_to_sheng','left')
            ->join('up_area ua3','ua3.district_id = a.order_to_shi','left')
            ->where($map)
            ->where('order_qy_user',$user_id)
            ->order('a.order_fb_time desc')
            ->field('a.*,ua.district as go_sheng,ua1.district as go_shi,
            ua2.district as to_sheng,ua3.district as to_shi')
//            ->field('a.order_intro,a.order_freight,a.con_type,a.order_goods_name,
//            a.order_num,a.order_true,a.order_type,a.order_status,
//            a.order_goods_ton,a.order_zc_time,
//            a.order_id,ua.district as go_sheng,ua1.district as go_shi,
//            ua2.district as to_sheng,ua3.district as to_shi')
            ->paginate(50);
        $where['a.order_status'] = array('IN',array(5,6));
        $where['a.order_type'] = 2;
        $where['a.order_qy_user']=$user_id;
        $map1['a.order_type'] = 1;
        $map1['a.order_status'] =array('IN',array(5,6));
        $map1['a.order_true'] =1;
        $map1['a.order_qy_user'] = $user_id;
        $num = Db::table('up_order')->alias('a')
            ->join('up_car_hwlx uch','uch.hwlx_id = a.hwlx_id','left')
            ->join('up_car_zxlx ucz','ucz.zxlx_id = a.zxlx_id','left')
            ->join('up_area ua','ua.district_id = a.order_go_sheng','left')
            ->join('up_area ua1','ua1.district_id = a.order_go_shi','left')
            ->join('up_area ua2','ua2.district_id = a.order_to_sheng','left')
            ->join('up_area ua3','ua3.district_id = a.order_to_shi','left')
            ->join('up_u_user uuu','uuu.user_id = a.order_jms_user','left')
            ->where(function ($query) use($where){
                $query->where($where);
            })
            ->whereOr(function ($query) use($map1){
                $query->where($map1);
            })
            ->count();
        //当前日期
        $sdefaultDate = date("Y-m-d");
//        $sdefaultDate = '2020-10-05';
        //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
        $first=1;
        //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
        $w=date('w',strtotime($sdefaultDate));
        //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
        $week_start=date('Y-m-d',strtotime("$sdefaultDate -".($w ? $w - $first : 6).' days'));
       //本周结束日期
//        print_r($week_start);
//        print_r($w);
//        die;
        $week_end=date('Y-m-d',strtotime("$week_start +6 days"));
        $where1['a.order_type'] = array('not in',array(3,4));
        $where1['a.order_status'] = array('IN',array(8,9));
        $where1['a.jiesuan'] = 2;
        $where1['a.order_paytime1'] = array('between',array($week_start,$week_end));
        $num1 = Db::table('up_order')->alias('a')
            ->join('up_car_hwlx uch','uch.hwlx_id = a.hwlx_id','left')
            ->join('up_car_zxlx ucz','ucz.zxlx_id = a.zxlx_id','left')
            ->join('up_area ua','ua.district_id = a.order_go_sheng','left')
            ->join('up_area ua1','ua1.district_id = a.order_go_shi','left')
            ->join('up_area ua2','ua2.district_id = a.order_to_sheng','left')
            ->join('up_area ua3','ua3.district_id = a.order_to_shi','left')
            ->join('up_u_user uuu','uuu.user_id = a.order_jms_user','left')
            ->where($where1)
            ->count();
        $this->assign('num',$num);
        $this->assign('num1',$num1);
        return $this->fetch ('order/index',['data'=>$data,'pages'=>$pages,'search'=>$search]);
    }

    //发布
    public function add()
    {
        if (request()->isAjax()) {
            $user_id = session('user_id');
            $list = Db::table('up_u_user')->where('user_id',$user_id)->find();
            //查询企业和加盟商是否签订合同
            $where['q_user_id'] = $list['user_id'];
            $where['j_user_id'] = $list['f_user_id'];
            $info = Db::table('up_contract')->where($where)->find();

            if($info['contract_id']==''){
                return json(['status'=>0,'msg'=>"没有和加盟商签订电子合同,请先签订电子合同,再发布货源"]);
            }else{
                if($info['contract_status']==1||$info['contract_status']==2||$info['contract_status']==3){
                    if($info['contract_status']==''){
                        return json(['status'=>0,'msg'=>"合同结算周期不能为空"]);
                    }
                    if($info['contract_date']==''){
                        return json(['status'=>0,'msg'=>"合同每月结算日期不能为空"]);
                    }
                }

            }
            //出发地
            $order_type = input('param.order_type');//1询价单  2直接发布

            if($order_type==1){
                $data['order_true'] = 2;
            }else{
                $data['order_true'] = 1;
            }
            if($info['contract_status']==1){
                $data['contract_status'] = 1;
            }
            if($info['contract_status']==2){
                $data['contract_status'] = 2;
            }
            if($info['contract_status']==3){
                $data['contract_status'] = 3;
            }
            $order_go_sheng = input('param.sheng');//出发省
            $order_go_shi = input('param.shi');//出发市
            $order_go_qu = input('param.qu');//出发区
            $order_go_address = input('param.order_go_address');//出发详情地址
            //目的地
            $order_to_sheng = input('param.sheng2');//出发地省
            $order_to_shi = input('param.shi2');//出发地市
            $order_to_qu = input('param.qu2');//出发地区
            $order_to_address = input('param.order_to_address');//出发地详情地址
            //货物
            $order_goods_name = input('param.order_goods_name');//货物名称
            $order_goods_ton = input('param.order_goods_ton');//货物(吨)
            $order_goods_m = input('param.order_goods_m');//货物(立方米)
            $order_freight = input('param.order_freight');//运费
            $order_zf_type = input('param.order_zf_type');//支付方式 1线上  2线下
            $order_zc_time = input('param.order_zc_time');//装车时间
            $zxlx_id = input('param.zxlx_id');//装卸类型
            $cx_id = input('param.cx_id');//车型(直接传值,以逗号分隔)
            $order_cc = input('param.order_cc');//车长(直接传值,以逗号分隔)
            $hwlx_id = input('param.hwlx_id');//货物类型
            $order_intro = input('param.order_intro');//备注
            $order_goods_img = input('param.order_goods_img');//货物照片
            if($order_type==2){
                if($order_freight==''){
                    return json(['status'=>0,'msg'=>"运费不能为空"]);
                }
            }
            $latlog = addresstolatlag($order_go_address);//获取经纬度
            $latlog1 = addresstolatlag($order_to_address);//获取经纬度

            $order_number = date('YmdHi') . str_pad(mt_rand(1, 9999), 6, '0', STR_PAD_LEFT).$user_id;
            if($info['contract_status']==1||$info['contract_status']==2||$info['contract_status']==3){
                $contract_date = date('Y-m-'.$info['contract_date'],strtotime($info['contract_status'].'month'));
                $data['order_contract_date'] =$contract_date;
                $data['con_type'] =1;
            }elseif ($info['contract_status']==4){
                $data['con_type'] =2;
            }elseif ($info['contract_status']==5){
                $data['con_type'] =3;
            }


            $data['order_num'] = $order_number;
            $data['order_type'] = $order_type;
            $data['order_go_sheng'] = $order_go_sheng;
            $data['order_go_shi'] = $order_go_shi;
            $data['order_go_qu'] = $order_go_qu;
            $data['order_go_address'] = $order_go_address;
            $data['order_go_lon'] = $latlog['log'];
            $data['order_go_lat'] = $latlog['lat'];
            $data['order_to_sheng'] = $order_to_sheng;
            $data['order_to_shi'] = $order_to_shi;
            $data['order_to_qu'] = $order_to_qu;
            $data['order_to_address'] = $order_to_address;
            $data['order_to_lon'] = $latlog1['log'];
            $data['order_to_lat'] = $latlog1['lat'];
            $data['order_goods_name'] = $order_goods_name;
            $data['order_goods_ton'] = $order_goods_ton;
            $data['order_goods_m'] = $order_goods_m;
            $data['order_freight'] = $order_freight;
            $data['order_zf_type'] = $order_zf_type;
            $data['order_zc_time'] = $order_zc_time;
            $data['zxlx_id'] = trim($zxlx_id,',');
            $data['cx_id'] = trim($cx_id,',');
            $data['order_cc'] = trim($order_cc,',');
            $data['hwlx_id'] = trim($hwlx_id,',');
            $data['order_intro'] = $order_intro;
            $data['order_goods_img'] = $order_goods_img;
            $data['order_fb_time'] =date('Y-m-d H:i:s');
            $data['order_fb_ymr'] =date('Y-m-d');
            $data['order_fb_ym'] =date('Y-m');
            $data['order_qy_user'] = $user_id;
            $data['order_jms_user'] = $list['f_user_id'];

            $district = Db::table('up_area')->where('district_id',$order_to_sheng)->value('district');
            $data['order_quyu'] = myArea($district);
            $res = Db::table('up_order')->insertGetId($data);
            //插入消息表
            $dataList['n_title'] = $list['user_gongsi'].'已向您发送一份询价单，请尽快处理';
            $dataList['n_type'] =  2;
            $dataList['n_notice_type'] = 2;
            $dataList['n_user_id'] = ','.$list['f_user_id'].',';
            $dataList['n_read'] = ',0,';
            $dataList['n_delete'] = ',0,';
            $dataList['n_time'] = date('Y-m-d H:i:s');
            $dataList['n_status'] = 2;
            Db::table('up_notice')->insertGetId($dataList);
            if($res){
                //推送
                $list1 = [];
                $v = (string)$list['f_user_id'];
                array_push($list1, $v);
                $code=2;
                $str = array('msg'=>$list['user_gongsi'].'已向您发送一份订单，请尽快处理','type'=>10,'order_id'=>$res);
                $str1 = $list['user_gongsi'].'已向您发送一份订单，请尽快处理';
                try{
                    $this->Jpush1(1, $list1, $str1, $str,$code);
                }catch(\Exception $e){

                }
                return json(['status'=>200,'msg'=>"发布成功"]);
            }else{
                return json(['status'=>0,'msg'=>'发布失败']);
            }
        }
        //车长
        $where['is_status'] = 1;
        $where['is_del'] = 1;
        $res = Db::table('up_car_cclb')->field('cclb_id,cclb_name')->order('cclb_id desc')->where($where)->select();
        //车型
        $where1['is_status'] = 1;
        $where1['is_del'] = 1;
        $res1 = Db::table('up_car_cx')->field('cx_id,cx_name')->where($where1)->select();
        //货物类型
        $where2['is_status'] = 1;
        $where2['is_del'] = 1;
        $res2 = Db::table('up_car_hwlx')->field('hwlx_id,hwlx_name')->where($where2)->select();
        //装修类型
        $where3['is_status'] = 1;
        $where3['is_del'] = 1;
        $res3 = Db::table('up_car_zxlx')->field('zxlx_id,zxlx_name')->where($where3)->select();
        $list['cc'] = $res;
        $list['cx'] = $res1;
        $list['hwlx'] = $res2;
        $list['zx'] = $res3;
        $this->assign('list', $list);
//        省市区
        // 省
        $province = Db::table('up_area')->where('level', 1)->field('district_id, district')->select();
        $this->assign([
            'province' => $province
        ]);
        return $this->fetch();
    }

    //实时订单
    public function detail1()
    {
        $field = 'order_zcsj_time,order_xhsj_time,order_status';
        $field .= ',order_go_lon,order_go_lat,order_to_lat,order_to_lon';
        $id = input('param.id');
        $where['order_id'] = $id;
        $res = Db::table('up_order')->alias('a')
            ->where($where)
            ->field($field)
            ->find();
        //总时长
        $res['tast_time'] = '';
        if($res['order_xhsj_time'] && $res['order_zcsj_time']){
            $times = strtotime($res['order_xhsj_time']) - strtotime($res['order_zcsj_time']);
            $hh = floor($times / 3600);
            $ii = floor(($times % 3600) / 60);
            $ss = $times % 60;
            $hh = str_pad("$hh",2,0,STR_PAD_LEFT);
            $ii = str_pad("$ii",2,0,STR_PAD_LEFT);
            $ss = str_pad("$ss",2,0,STR_PAD_LEFT);
            $res['tast_time'] = $hh . ':' . $ii . ':' . $ss;

        }
//
        $baifenbi = 0; //代表没有卸货
        if($res['order_xhsj_time']) {
            $baifenbi = 1; //代表已经卸货了，结束了，进度百分之百
        }
//
        $res['time_cha'] = -1; //装货时间和现在的差，-1代表还没有装货
        if($res['order_zcsj_time']) {
            //装车时间跟当前时间的差额
            $res['time_cha'] = time() - strtotime($res['order_zcsj_time']);
        }
        $this->assign('nowTime',date('Y-m-d H:i:s'));
        $this->assign('data',$res);
        $this->assign('baifenbi',$baifenbi);
        //经纬度点，和APP一致
        $jwd = Db::table('up_order_dot')->where('order_id',$id)->order('dot_id desc')->find();
        $mwwX = 0;
        $mwwD = 0;
        if($jwd){
            $mwwX = $jwd['dot_lat'];
            $mwwD = $jwd['dot_lon'];
        }
        $this->assign('mwwX',$mwwX);
        $this->assign('mwwD',$mwwD);
        return $this->fetch();
    }

    //详情
    public function detail()
    {
        $id = input('param.id');
        $where['a.order_id'] = $id;
        $res = Db::table('up_order')->alias('a')
            ->join('up_car_hwlx uch','uch.hwlx_id = a.hwlx_id','left')
            ->join('up_car_zxlx ucz','ucz.zxlx_id = a.zxlx_id','left')
            ->join('up_area ua','ua.district_id = a.order_go_sheng','left')
            ->join('up_area ua1','ua1.district_id = a.order_go_shi','left')
            ->join('up_area ua2','ua2.district_id = a.order_to_sheng','left')
            ->join('up_area ua3','ua3.district_id = a.order_to_shi','left')
            ->where($where)
            ->field('a.order_zc_goods_img,a.order_num,a.order_go_address,a.order_to_address,a.order_goods_name,
                a.order_true,ucz.zxlx_name,a.order_goods_m,a.order_type,a.order_goods_ton,
                a.order_status,a.order_zc_time,a.cx_id as cx_name,a.order_freight,a.con_type,
                uch.hwlx_name,a.order_cc,a.order_goods_ton,a.order_zc_time,a.cx_id,a.order_intro,
                a.order_id,ua.district as go_sheng,ua1.district as go_shi,a.order_goods_img,a.order_xh_goods_img,
                ua2.district as to_sheng,ua3.district as to_shi
            ')
            ->find();
        $res['img'] = array_filter(explode(',',$res['order_goods_img']));
        $res['img1'] = array_filter(explode(',',$res['order_xh_goods_img']));
        $res['img2'] = array_filter(explode(',',$res['order_zc_goods_img']));
        $this->assign('res',$res);
        return $this->fetch();
    }

    //评价
    public function comment()
    {
        if(request()->isAjax()){
            $user_id = session('user_id');
            extract(input());
            $evaluate_bq = input('param.evaluate_bq');//评价标签
            $evaluate_bq = trim($evaluate_bq,',');
            $evaluate_star = input('param.evaluate_star');//评价星级
            $evaluate_review = input('param.evaluate_review');//1好评(大于4星)  2中评(4星） 3差评(1-3差评)
            $evaluate_content = input('param.evaluate_content');//评价内容
            $evaluate_b_user_id = input('param.evaluate_b_user_id');//被评价人
            $evaluate_img = input('param.evaluate_img');//评价图片
            $order_id = input('param.order_id');//图片

            $data['evaluate_p_user_id'] = $user_id;
            $data['evaluate_b_user_id'] = $evaluate_b_user_id;
            $data['order_id'] = $order_id;
            $data['evaluate_type'] = 2;
            $data['evaluate_content'] = $evaluate_content;
            $data['evaluate_star'] = $evaluate_star;
            $data['evaluate_bq'] = $evaluate_bq;
            $data['evaluate_review'] = $evaluate_review;
            $data['evaluate_img'] = $evaluate_img;
            $data['evaluate_time'] = date('Y-m-d H:i:s');
            $res = Db::table('up_order_evaluate')->insertGetId($data);
            //查询加盟商是否对这个订单是否评价
            $result = Db::table('up_order')->where('order_id',$order_id)->field('order_id,jms_pj')->find();
            if($result['jms_pj']==1){
                Db::table('up_order')->where('order_id',$order_id)->setField('jms_pj',2);
            }
            //查询这个加盟商和司机是否都评价完成
            $result1 = Db::table('up_order')->where('order_id',$order_id)->field('order_status,order_id,jms_pj,sj_pj')->find();
            if($result1['order_status']==8){//待评价
                if($result1['jms_pj']==2&&$result1['sj_pj']==2){//司机和加盟商都评价过
                    Db::table('up_order')->where('order_id',$order_id)->setField('order_status',9);
                }
            }
            if($res){
                return json(['status'=>200,'msg'=>"成功"]);
            }else{
                return json(['status'=>100,'msg'=>"失败"]);
            }
        }
        $id = input('param.id');
        $this->assign('id',$id);
        $order = Db::table('up_order')->where('order_id',$id)
            ->field('order_jms_user,order_num')->find();
        $this->assign('order',$order);
        return $this->fetch();
    }

    public function daochu(){
        
        $keyword= input('keyword');
        $map=array();
        if($keyword!=''){
            $map['a.order_num|a.order_goods_name'] = array("like","$keyword");
        }
        $map['order_qy_user']= session('user_id');
        $lists = Db::name('order')->alias('a')
            ->join('up_u_user uuu','uuu.user_id = a.order_dirver_user','left')
            ->join('up_u_user uuu1','uuu1.user_id = a.order_qy_user','left')
            ->join('up_area ua','ua.district_id = a.order_go_sheng','left')
            ->join('up_area ua1','ua1.district_id = a.order_go_shi','left')
            ->join('up_area ua2','ua2.district_id = a.order_to_sheng','left')
            ->join('up_area ua3','ua3.district_id = a.order_to_shi','left')
            ->where($map)
            ->field('a.order_id,a.order_status,a.order_num,a.order_zc_time,
            a.order_dzxy_yf,a.order_freight,uuu.user_username,uuu.user_phone,uuu1.user_gongsi
                ,uuu1.user_username as qy_username,uuu1.user_phone as qy_phone,
                 ua.district as go_sheng,ua1.district as go_shi,
                        ua2.district as to_sheng,ua3.district as to_shi')
            ->order('a.order_fb_time desc')
            ->select();
//        foreach($lists as $k => $v){
//            $lists[$k]['user_phone'] = "\t".$v['user_phone']."\t";
//        }
        foreach ($lists as $key=>$vo){
            $vo['go_address'] = $vo['go_sheng'].'-'.$vo['go_shi'];
            $vo['to_address'] = $vo['to_sheng'].'-'.$vo['to_shi'];
            if(in_array($vo['order_status'],array(2,3,4,5,6,7))){
                $vo['order_status'] = '进行中';
            }elseif (in_array($vo['order_status'],array(8,9))){
                $vo['order_status'] = '完成';
            }
            //税赋
            $price1 = ($vo['order_freight']/1.09)*0.09;
            //保险成本
            $price2 = $vo['order_freight']*0.06;
            //平台抽成
            if($vo['order_freight']<30000){
                $price3 = $vo['order_freight']*0.0358;
            }elseif ($vo['order_freight']>=30000&&$vo['order_freight']<300000){
                $price3 = $vo['order_freight']*0.0258;
            }elseif ($vo['order_freight']>=300000){
                $price3 = $vo['order_freight']*0.0198;
            }
            $price4 = $vo['order_freight'] - $price1- $price2- $price3;
            $vo['price'] = number_format($price4, 2);
            $lists[$key]['order_id'] = $vo['order_id'];
            $lists[$key]['order_status_name'] = $vo['order_status'];
            $lists[$key]['order_num'] = "\t".$vo['order_num']."\t";
            $lists[$key]['price'] = "\t".$vo['price']."\t";
            $lists[$key]['user_username'] = "\t".$vo['user_username']."\t";
            $lists[$key]['user_phone'] = "\t".$vo['user_phone']."\t";
            $lists[$key]['qy_username'] = "\t".$vo['qy_username']."\t";
            $lists[$key]['qy_phone'] = "\t".$vo['qy_phone']."\t";
            $lists[$key]['go_address'] = "\t".$vo['go_address']."\t";
            $lists[$key]['to_address'] = "\t".$vo['to_address']."\t";
            $lists[$key]['order_zc_time'] = "\t".$vo['order_zc_time']."\t";
            $lists[$key]['order_dzxy_yf'] = "\t".$vo['order_dzxy_yf']."\t";
            $lists[$key]['order_freight'] = "\t".$vo['order_freight']."\t";
        }
        $cellname = [
            ['order_id','ID',20,'LEFT'],
            ['order_status_name','订单状态',20,'LEFT'],
            ['order_num','订单号',20,'LEFT'],
            ['user_gongsi','企业名称',20,'LEFT'],
            ['price','本单获得金额',20,'LEFT'],
            ['user_username','司机昵称',20,'LEFT'],
            ['user_phone','司机号码',20,'LEFT'],
            ['qy_username','发布人姓名',20,'LEFT'],
            ['qy_phone','发布人手机号码',20,'LEFT'],
            ['go_address','出发地',20,'LEFT'],
            ['to_address','目的地',20,'LEFT'],
            ['order_zc_time','装车时间',20,'LEFT'],
            ['order_dzxy_yf','定金金额',20,'LEFT'],
            ['order_freight','整单金额',20,'LEFT'],
        ];
        $res = exportExcel('订单列表', 'Looks', $cellname, $lists);
        return json($res);
    }
}